

<!DOCTYPE html>
<html class="writer-html5" lang="en" >
<head>
  <meta charset="utf-8" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  
  <title>mindspore.scipy.optimize.minimize &mdash; MindSpore master documentation</title>
  

  
  <link rel="stylesheet" href="../../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />

  
  

  
  

  

  
  <!--[if lt IE 9]>
    <script src="../../../../_static/js/html5shiv.min.js"></script>
  <![endif]-->
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../../../" src="../../../../_static/documentation_options.js"></script>
        <script src="../../../../_static/jquery.js"></script>
        <script src="../../../../_static/underscore.js"></script>
        <script src="../../../../_static/doctools.js"></script>
        <script src="../../../../_static/language_data.js"></script>
        <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    
    <script type="text/javascript" src="../../../../_static/js/theme.js"></script>

    
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../../../index.html" class="icon icon-home"> MindSpore
          

          
          </a>

          
            
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        
        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption"><span class="caption-text">MindSpore Python API</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.html">mindspore</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.common.initializer.html">mindspore.common.initializer</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.communication.html">mindspore.communication</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.compression.html">mindspore.compression</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.context.html">mindspore.context</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.dataset.html">mindspore.dataset</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.dataset.audio.html">mindspore.dataset.audio</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.dataset.config.html">mindspore.dataset.config</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.dataset.text.html">mindspore.dataset.text</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.dataset.transforms.html">mindspore.dataset.transforms</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.dataset.vision.html">mindspore.dataset.vision</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.mindrecord.html">mindspore.mindrecord</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.nn.html">mindspore.nn</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.nn.probability.html">mindspore.nn.probability</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.nn.transformer.html">mindspore.nn.transformer</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.numpy.html">mindspore.numpy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.ops.html">mindspore.ops</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.parallel.html">mindspore.parallel</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.parallel.nn.html">mindspore.parallel.nn</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.profiler.html">mindspore.profiler</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.scipy.html">mindspore.scipy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.train.html">mindspore.train</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../api_python/mindspore.boost.html">mindspore.boost</a></li>
</ul>
<p class="caption"><span class="caption-text">MindSpore C++ API</span></p>
<ul>
<li class="toctree-l1"><a class="reference external" href="https://www.mindspore.cn/lite/api/zh-CN/master/api_cpp/mindspore.html">MindSpore Lite↗</a></li>
</ul>

            
          
        </div>
        
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../../../index.html">MindSpore</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          

















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../../../index.html" class="icon icon-home"></a> &raquo;</li>
        
          <li><a href="../../../index.html">Module code</a> &raquo;</li>
        
      <li>mindspore.scipy.optimize.minimize</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <h1>Source code for mindspore.scipy.optimize.minimize</h1><div class="highlight"><pre>
<span></span><span class="c1"># Copyright 2021 Huawei Technologies Co., Ltd</span>
<span class="c1">#</span>
<span class="c1"># Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span>
<span class="c1"># you may not use this file except in compliance with the License.</span>
<span class="c1"># You may obtain a copy of the License at</span>
<span class="c1">#</span>
<span class="c1"># http://www.apache.org/licenses/LICENSE-2.0</span>
<span class="c1">#</span>
<span class="c1"># Unless required by applicable law or agreed to in writing, software</span>
<span class="c1"># distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span>
<span class="c1"># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span>
<span class="c1"># See the License for the specific language governing permissions and</span>
<span class="c1"># limitations under the License.</span>
<span class="c1"># ============================================================================</span>
<span class="sd">&quot;&quot;&quot;minimize&quot;&quot;&quot;</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Optional</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">NamedTuple</span>

<span class="kn">from</span> <span class="nn">...common</span> <span class="kn">import</span> <span class="n">Tensor</span>

<span class="kn">from</span> <span class="nn">._bfgs</span> <span class="kn">import</span> <span class="n">minimize_bfgs</span>


<span class="k">class</span> <span class="nc">OptimizeResults</span><span class="p">(</span><span class="n">NamedTuple</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Object holding optimization results.</span>

<span class="sd">    Args:</span>
<span class="sd">        x (Tensor): final solution.</span>
<span class="sd">        success (bool): ``True`` if optimization succeeded.</span>
<span class="sd">        status (int): solver specific return code. 0 means converged (nominal),</span>
<span class="sd">            1=max BFGS iters reached, 3=zoom failed, 4=saddle point reached,</span>
<span class="sd">            5=max line search iters reached, -1=undefined</span>
<span class="sd">        fun (float): final function value.</span>
<span class="sd">        jac (Tensor): final jacobian array.</span>
<span class="sd">        hess_inv (Tensor, optional): final inverse Hessian estimate.</span>
<span class="sd">        nfev (int): number of function calls used.</span>
<span class="sd">        njev (int): number of gradient evaluations.</span>
<span class="sd">        nit (int): number of iterations of the optimization algorithm.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">x</span><span class="p">:</span> <span class="n">Tensor</span>
    <span class="n">success</span><span class="p">:</span> <span class="nb">bool</span>
    <span class="n">status</span><span class="p">:</span> <span class="nb">int</span>
    <span class="n">fun</span><span class="p">:</span> <span class="nb">float</span>
    <span class="n">jac</span><span class="p">:</span> <span class="n">Tensor</span>
    <span class="n">hess_inv</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">Tensor</span><span class="p">]</span>
    <span class="n">nfev</span><span class="p">:</span> <span class="nb">int</span>
    <span class="n">njev</span><span class="p">:</span> <span class="nb">int</span>
    <span class="n">nit</span><span class="p">:</span> <span class="nb">int</span>


<div class="viewcode-block" id="minimize"><a class="viewcode-back" href="../../../../api_python/scipy/mindspore.scipy.optimize.minimize.html#mindspore.scipy.optimize.minimize">[docs]</a><span class="k">def</span> <span class="nf">minimize</span><span class="p">(</span><span class="n">func</span><span class="p">,</span> <span class="n">x0</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(),</span> <span class="o">*</span><span class="p">,</span> <span class="n">method</span><span class="p">,</span> <span class="n">tol</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">options</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Minimization of scalar function of one or more variables.</span>

<span class="sd">    This API for this function matches SciPy with some minor deviations:</span>

<span class="sd">    - Gradients of ``func`` are calculated automatically using MindSpore&#39;s autodiff</span>
<span class="sd">      support when required.</span>
<span class="sd">    - The ``method`` argument is required. You must specify a solver.</span>
<span class="sd">    - Various optional arguments in the SciPy interface have not yet been</span>
<span class="sd">      implemented.</span>
<span class="sd">    - Optimization results may differ from SciPy due to differences in the line</span>
<span class="sd">      search implementation.</span>

<span class="sd">    It does not yet support differentiation or arguments in the form of</span>
<span class="sd">    multi-dimensional Tensor, but support for both is planned.</span>

<span class="sd">    Args:</span>
<span class="sd">      func (Callable): the objective function to be minimized, :math:`fun(x, *args) -&gt; float`,</span>
<span class="sd">        where `x` is a 1-D array with shape :math:`(n,)` and `args` is a tuple</span>
<span class="sd">        of the fixed parameters needed to completely specify the function.</span>
<span class="sd">        `fun` must support differentiation.</span>
<span class="sd">      x0 (Tensor): initial guess. Array of real elements of size :math:`(n,)`, where `n` is</span>
<span class="sd">        the number of independent variables.</span>
<span class="sd">      args (Tuple): extra arguments passed to the objective function. Default: ().</span>
<span class="sd">      method (str): solver type. Currently only `&quot;BFGS&quot;` is supported.</span>
<span class="sd">      tol (float, optional): tolerance for termination. For detailed control, use solver-specific</span>
<span class="sd">        options. Default: None.</span>
<span class="sd">      options (Mapping[str, Any], optional): a dictionary of solver options. All methods accept the following</span>
<span class="sd">        generic options, Default: None.</span>

<span class="sd">        - maxiter (int): Maximum number of iterations to perform. Depending on the</span>
<span class="sd">          method each iteration may use several function evaluations.</span>

<span class="sd">    Returns:</span>
<span class="sd">        OptimizeResults, object holding optimization results.</span>

<span class="sd">    Supported Platforms:</span>
<span class="sd">        ``CPU`` ``GPU``</span>

<span class="sd">    Examples:</span>
<span class="sd">        &gt;&gt;&gt; import numpy as onp</span>
<span class="sd">        &gt;&gt;&gt; from mindspore.scipy.optimize import minimize</span>
<span class="sd">        &gt;&gt;&gt; from mindspore.common import Tensor</span>
<span class="sd">        &gt;&gt;&gt; x0 = Tensor(onp.zeros(2).astype(onp.float32))</span>
<span class="sd">        &gt;&gt;&gt; def func(p):</span>
<span class="sd">        &gt;&gt;&gt;     x, y = p</span>
<span class="sd">        &gt;&gt;&gt;     return (x ** 2 + y - 11.) ** 2 + (x + y ** 2 - 7.) ** 2</span>
<span class="sd">        &gt;&gt;&gt; res = minimize(func, x0, method=&#39;BFGS&#39;, options=dict(maxiter=None, gtol=1e-6))</span>
<span class="sd">        &gt;&gt;&gt; res.x</span>
<span class="sd">        Tensor(shape=[2], dtype=Float32, value= [ 3.00000000e+00,  2.00000000e+00])</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">options</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">options</span> <span class="o">=</span> <span class="p">{}</span>

    <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="nb">tuple</span><span class="p">):</span>
        <span class="n">msg</span> <span class="o">=</span> <span class="s2">&quot;args argument to mindspore.scipy.optimize.minimize must be a tuple, got </span><span class="si">{}</span><span class="s2">&quot;</span>
        <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="n">msg</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="p">))</span>

    <span class="k">def</span> <span class="nf">fun_with_args</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
        <span class="k">def</span> <span class="nf">inner_func</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">func</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>

        <span class="k">return</span> <span class="n">inner_func</span>

    <span class="k">if</span> <span class="n">method</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;bfgs&#39;</span><span class="p">:</span>
        <span class="n">results</span> <span class="o">=</span> <span class="n">minimize_bfgs</span><span class="p">(</span><span class="n">fun_with_args</span><span class="p">(</span><span class="n">args</span><span class="p">),</span> <span class="n">x0</span><span class="p">,</span> <span class="o">**</span><span class="n">options</span><span class="p">)</span>
        <span class="n">success</span> <span class="o">=</span> <span class="n">results</span><span class="o">.</span><span class="n">converged</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">results</span><span class="o">.</span><span class="n">failed</span>
        <span class="k">return</span> <span class="n">OptimizeResults</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="n">results</span><span class="o">.</span><span class="n">x_k</span><span class="p">,</span>
                               <span class="n">success</span><span class="o">=</span><span class="n">success</span><span class="p">,</span>
                               <span class="n">status</span><span class="o">=</span><span class="n">results</span><span class="o">.</span><span class="n">status</span><span class="p">,</span>
                               <span class="n">fun</span><span class="o">=</span><span class="n">results</span><span class="o">.</span><span class="n">f_k</span><span class="p">,</span>
                               <span class="n">jac</span><span class="o">=</span><span class="n">results</span><span class="o">.</span><span class="n">g_k</span><span class="p">,</span>
                               <span class="n">hess_inv</span><span class="o">=</span><span class="n">results</span><span class="o">.</span><span class="n">H_k</span><span class="p">,</span>
                               <span class="n">nfev</span><span class="o">=</span><span class="n">results</span><span class="o">.</span><span class="n">nfev</span><span class="p">,</span>
                               <span class="n">njev</span><span class="o">=</span><span class="n">results</span><span class="o">.</span><span class="n">ngev</span><span class="p">,</span>
                               <span class="n">nit</span><span class="o">=</span><span class="n">results</span><span class="o">.</span><span class="n">k</span><span class="p">)</span>

    <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Method </span><span class="si">{}</span><span class="s2"> not recognized&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">method</span><span class="p">))</span></div>
</pre></div>

           </div>
           
          </div>
          <footer>

  <hr/>

  <div role="contentinfo">
    <p>
        &#169; Copyright 2021, MindSpore.

    </p>
  </div>
    
    
    
    Built with <a href="https://www.sphinx-doc.org/">Sphinx</a> using a
    
    <a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
    
    provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>
        </div>
      </div>

    </section>

  </div>
  

  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
   

</body>
</html>